package org.lagou.edu.utils;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.lagou.edu.controller.dto.ShopInfo;

import java.util.concurrent.TimeUnit;

/**
 * @author: shiding
 * @data: 2022/7/16 23:51
 **/
public class ShopGuavaCacheUtil {

    public static final String SHOP_PREFIX = "STOCK_SHOP:";
    public static Cache<Long, Object> shopCache = CacheBuilder.newBuilder()
            //设置缓存初始大小，应该合理设置，后续会扩容
            .initialCapacity(10)
            //最大值
            .maximumSize(100)
            //并发数设置
            .concurrencyLevel(5)
            //缓存过期时间，写入后10分钟过期
            .expireAfterWrite(600, TimeUnit.SECONDS)
            // 此缓存对象经过多少秒没有被访问则过期。
            .expireAfterAccess(10, TimeUnit.SECONDS)
            //统计缓存命中率
            .recordStats()
            .build();


    public static ShopInfo getShop(Long id) {
        return (ShopInfo) shopCache.getIfPresent(id);
    }

    public static void setShop(Long id, Object shopInfo) {
        shopCache.put(id, shopInfo);
    }
}
